package com.dwjm.goods;

import com.dwjm.CommonResult;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/getGoodById")
public class GetGoodByIdServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        String idStr = req.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            resp.getWriter().write(new Gson().toJson(CommonResult.fail(400, "缺少参数id")));
            return;
        }

        try {
            int id = Integer.parseInt(idStr);
            GoodDao goodDao = new GoodDaolpml();
            Goods goods = goodDao.getById(id);

            if (goods != null) {
                resp.getWriter().write(new Gson().toJson(CommonResult.success(goods)));
            } else {
                resp.getWriter().write(new Gson().toJson(CommonResult.fail(404, "商品未找到")));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(new Gson().toJson(CommonResult.fail(400, "id格式错误")));
        }
    }
}
